package com.tangruojie.controller;

import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/servletOutputStream")
public class ServletOutputStreamController {

    /**
     * 输出纯文本
     *
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "/text", produces = "text/plain;charset=utf-8")
    public void outputTest(HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write("Hello ServletOutputStream".getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }

    /**
     * 输出图片
     *
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "/image", produces = MediaType.IMAGE_PNG_VALUE)
    public void outputImage(HttpServletResponse response) throws IOException {
        ClassPathResource classPathResource = new ClassPathResource("image/1.png");
        InputStream inputStream = classPathResource.getInputStream();
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[1024];
        while (inputStream.read(bytes) != -1) {
            outputStream.write(bytes);
        }
        outputStream.flush();
        outputStream.close();
        inputStream.close();
    }

    /**
     * 下载文件
     * HTTP 协议规范本身就不允许在 header 中使用非 ISO-8859-1 编码的字符。
     *
     * @param response
     * @throws IOException
     */
    @GetMapping(value = "/download", produces = MediaType.IMAGE_PNG_VALUE)
    public void download(HttpServletResponse response) throws IOException {
        /**
         * 告诉浏览器，这个请求返回的是一个文件，而不是一个网页
         */
        response.setHeader("Content-Disposition", "attachment;filename=1.pdf");
        ClassPathResource classPathResource = new ClassPathResource("pdf/1.pdf");
        InputStream inputStream = classPathResource.getInputStream();
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[1024];
        while (inputStream.read(bytes) != -1) {
            outputStream.write(bytes);
        }
        outputStream.flush();
        outputStream.close();
        inputStream.close();
    }

}
